import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _excluded = ["children", "trigger", "onVisibleChange", "modalProps", "onFinish", "submitTimeout", "title", "width", "visible"];
import { Fragment as _Fragment, jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { ConfigProvider, Modal } from 'antd-v4';
import merge from 'lodash.merge';
import useMergedState from "rc-util/es/hooks/useMergedState";
import { noteOnce } from "rc-util/es/warning";
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { BaseForm } from '../../BaseForm';

function ModalForm(_ref) {
  var _context$locale3, _context$locale3$Moda, _context$locale4, _context$locale4$Moda;

  var children = _ref.children,
      trigger = _ref.trigger,
      onVisibleChange = _ref.onVisibleChange,
      modalProps = _ref.modalProps,
      onFinish = _ref.onFinish,
      submitTimeout = _ref.submitTimeout,
      title = _ref.title,
      width = _ref.width,
      propVisible = _ref.visible,
      rest = _objectWithoutProperties(_ref, _excluded);

  noteOnce( // eslint-disable-next-line @typescript-eslint/dot-notation
  !rest['footer'] || !(modalProps === null || modalProps === void 0 ? void 0 : modalProps.footer), 'ModalForm 是一个 ProForm 的特殊布局，如果想自定义按钮，请使用 submit.render 自定义。');
  var context = useContext(ConfigProvider.ConfigContext);

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      forceUpdate = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

  var _useMergedState = useMergedState(!!propVisible, {
    value: propVisible,
    onChange: onVisibleChange
  }),
      _useMergedState2 = _slicedToArray(_useMergedState, 2),
      visible = _useMergedState2[0],
      setVisible = _useMergedState2[1];

  var footerRef = useRef(null);
  var footerDomRef = useCallback(function (element) {
    if (footerRef.current === null && element) {
      forceUpdate([]);
    }

    footerRef.current = element;
  }, []);
  var formRef = useRef();
  useEffect(function () {
    if (visible && propVisible) {
      onVisibleChange === null || onVisibleChange === void 0 ? void 0 : onVisibleChange(true);
    } // eslint-disable-next-line react-hooks/exhaustive-deps

  }, [propVisible, visible]);
  var triggerDom = useMemo(function () {
    if (!trigger) {
      return null;
    }

    return /*#__PURE__*/React.cloneElement(trigger, _objectSpread(_objectSpread({
      key: 'trigger'
    }, trigger.props), {}, {
      onClick: function () {
        var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(e) {
          var _trigger$props, _trigger$props$onClic;

          return _regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  setVisible(!visible);
                  (_trigger$props = trigger.props) === null || _trigger$props === void 0 ? void 0 : (_trigger$props$onClic = _trigger$props.onClick) === null || _trigger$props$onClic === void 0 ? void 0 : _trigger$props$onClic.call(_trigger$props, e);

                case 2:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));

        function onClick(_x) {
          return _onClick.apply(this, arguments);
        }

        return onClick;
      }()
    }));
  }, [setVisible, trigger, visible]);
  var submitterConfig = useMemo(function () {
    var _ref2, _modalProps$okText, _context$locale, _context$locale$Modal, _ref3, _modalProps$cancelTex, _context$locale2, _context$locale2$Moda;

    if (rest.submitter === false) {
      return false;
    }

    return merge({
      searchConfig: {
        submitText: (_ref2 = (_modalProps$okText = modalProps === null || modalProps === void 0 ? void 0 : modalProps.okText) !== null && _modalProps$okText !== void 0 ? _modalProps$okText : (_context$locale = context.locale) === null || _context$locale === void 0 ? void 0 : (_context$locale$Modal = _context$locale.Modal) === null || _context$locale$Modal === void 0 ? void 0 : _context$locale$Modal.okText) !== null && _ref2 !== void 0 ? _ref2 : '确认',
        resetText: (_ref3 = (_modalProps$cancelTex = modalProps === null || modalProps === void 0 ? void 0 : modalProps.cancelText) !== null && _modalProps$cancelTex !== void 0 ? _modalProps$cancelTex : (_context$locale2 = context.locale) === null || _context$locale2 === void 0 ? void 0 : (_context$locale2$Moda = _context$locale2.Modal) === null || _context$locale2$Moda === void 0 ? void 0 : _context$locale2$Moda.cancelText) !== null && _ref3 !== void 0 ? _ref3 : '取消'
      },
      resetButtonProps: {
        preventDefault: true,
        // 提交表单loading时，不可关闭弹框
        disabled: submitTimeout ? loading : undefined,
        onClick: function onClick(e) {
          var _modalProps$onCancel;

          setVisible(false);
          modalProps === null || modalProps === void 0 ? void 0 : (_modalProps$onCancel = modalProps.onCancel) === null || _modalProps$onCancel === void 0 ? void 0 : _modalProps$onCancel.call(modalProps, e);
        }
      }
    }, rest.submitter);
  }, [(_context$locale3 = context.locale) === null || _context$locale3 === void 0 ? void 0 : (_context$locale3$Moda = _context$locale3.Modal) === null || _context$locale3$Moda === void 0 ? void 0 : _context$locale3$Moda.cancelText, (_context$locale4 = context.locale) === null || _context$locale4 === void 0 ? void 0 : (_context$locale4$Moda = _context$locale4.Modal) === null || _context$locale4$Moda === void 0 ? void 0 : _context$locale4$Moda.okText, modalProps, rest.submitter, setVisible, loading, submitTimeout]);
  var contentRender = useCallback(function (formDom, submitter) {
    return _jsxs(_Fragment, {
      children: [formDom, footerRef.current && submitter ? /*#__PURE__*/createPortal(submitter, footerRef.current) : submitter]
    });
  }, []);
  var onFinishHandle = useCallback( /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(values) {
      var response, timer, result;
      return _regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              response = onFinish === null || onFinish === void 0 ? void 0 : onFinish(values);

              if (submitTimeout && response instanceof Promise) {
                setLoading(true);
                timer = setTimeout(function () {
                  return setLoading(false);
                }, submitTimeout);
                response.finally(function () {
                  clearTimeout(timer);
                  setLoading(false);
                });
              }

              _context2.next = 4;
              return response;

            case 4:
              result = _context2.sent;

              // 返回真值，关闭弹框
              if (result) {
                setVisible(false);
              }

              return _context2.abrupt("return", result);

            case 7:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function (_x2) {
      return _ref4.apply(this, arguments);
    };
  }(), [onFinish, setVisible, submitTimeout]);
  return _jsxs(_Fragment, {
    children: [_jsx(Modal, _objectSpread(_objectSpread({
      title: title,
      width: width || 800
    }, modalProps), {}, {
      visible: visible,
      onCancel: function onCancel(e) {
        var _modalProps$onCancel2;

        // 提交表单loading时，阻止弹框关闭
        if (submitTimeout && loading) return;
        setVisible(false);
        modalProps === null || modalProps === void 0 ? void 0 : (_modalProps$onCancel2 = modalProps.onCancel) === null || _modalProps$onCancel2 === void 0 ? void 0 : _modalProps$onCancel2.call(modalProps, e);
      },
      footer: rest.submitter !== false && _jsx("div", {
        ref: footerDomRef,
        style: {
          display: 'flex',
          justifyContent: 'flex-end'
        }
      }),
      children: _jsx(BaseForm, _objectSpread(_objectSpread({
        formComponentType: "ModalForm",
        layout: "vertical",
        formRef: formRef
      }, rest), {}, {
        submitter: submitterConfig,
        onFinish: function () {
          var _onFinish = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(values) {
            var _rest$formRef$current, _rest$formRef;

            var result, form;
            return _regeneratorRuntime().wrap(function _callee3$(_context3) {
              while (1) {
                switch (_context3.prev = _context3.next) {
                  case 0:
                    _context3.next = 2;
                    return onFinishHandle(values);

                  case 2:
                    result = _context3.sent;
                    form = (_rest$formRef$current = (_rest$formRef = rest.formRef) === null || _rest$formRef === void 0 ? void 0 : _rest$formRef.current) !== null && _rest$formRef$current !== void 0 ? _rest$formRef$current : formRef.current; // 返回真值，重置表单

                    if (result && form) {
                      form.resetFields();
                    }

                    return _context3.abrupt("return", result);

                  case 6:
                  case "end":
                    return _context3.stop();
                }
              }
            }, _callee3);
          }));

          function onFinish(_x3) {
            return _onFinish.apply(this, arguments);
          }

          return onFinish;
        }(),
        contentRender: contentRender,
        children: children
      }))
    })), triggerDom]
  });
}

export { ModalForm };